package com.fwj.utils;

import com.fwj.config.Constants;
import com.fwj.exception.EsbSynException;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.log4j.Logger;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EsbsynUtil {

    private static Logger logger = Logger.getLogger(EsbsynUtil.class);
    public static void ipCheck(String[] datas)   {
        String returnMessage = "";

        if(datas==null||datas.length==0)
            throw new EsbSynException("读取的配置文件为空.");
        for (int i = 0; i < datas.length; i++) {

            String ips = "";
            String data = datas[i];
            int l = i + 1;
            if (data.indexOf(",") <= -1) {
                returnMessage += "第" + l + "行缺少“,”分隔符！";
                continue;
            } else {
                ips = datas[i].split(",")[1];

                if (isIpv4(ips)) {
                    continue;
                }

                if (ips.indexOf("|") > -1) {
                    String ipsstr[] = ips.split("\\|");
                    int o =1;
                    for (int j = 0; j < ipsstr.length; j++) {
                        if (!isIpv4(ipsstr[j])) {
                         //   returnMessage += "第" + l + "行IP格式出错！";

                            if(o>0){
                                returnMessage += "\n第" + l + "行出错！\n";
                                --o;
                            }
                            returnMessage += "第" + (j+1) + "对IP格式出错！";
                            continue;
                        }
                    }
                } else {
                    if (!isIpv4(ips)) {
                        returnMessage += "第" + l + "行IP格式出错！";
                        continue;
                    }
                    returnMessage += "第" + l + "行缺少“|”分隔符！";
                    continue;
                }
            }
        }
        if (!"".equals(returnMessage)) {
            returnMessage += "请检查！";
            logger.error(Constants.syn_datafile + "文件格式出错，请检查！");
            logger.error(returnMessage);


            throw new EsbSynException(Constants.syn_datafile + "文件格式出错，请检查！");
        }
    }
    public static String random(){
        return RandomStringUtils.random(5, true, true).toLowerCase();
    }
    
    
    /**
     * 判断IP格式
     *
     * @param ipAddress
     * @return
     */
    public static boolean isIpv4(String ipAddress) {

        String ip = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
                + "(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                + "(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                + "(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d):\\d{2,5}$";


        Pattern pattern = Pattern.compile(ip);
        Matcher matcher = pattern.matcher(ipAddress);
        return matcher.matches();

    }

    /**
     * 移动文件到历史文件夹
     *
     * @param listNames
     * @param destPath
     * @return
     */
    public static void move(List<String> listNames, String destPath) {
        if(listNames!=null&&listNames.size()>0){
            for (int i = 0; i < listNames.size(); i++) {
                String fileName = listNames.get(i);
                File file = new File(fileName);
                File dir = new File(destPath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                file.renameTo(new File(dir, file.getName()));

            }

        }

        logger.info("文件复制到" + destPath + "成功!!!");
    }
    /**
     * 获取目录下所有文件(按时间排序)
     *
     * @param path
     * @return
     * @throws IOException
     */
    public static List getFileSort(List fileList, String path) throws IOException {
        if (fileList != null && fileList.size() > 0) {
            Collections.sort(fileList, new Comparator<File>() {
                public int compare(File file, File newFile) {
                    //日期类型进行排序
                    long filetime = file.lastModified();
                    long newFiletime = newFile.lastModified();
                    //由原来的降序,修改为升序
                    if (filetime > newFiletime) {
                        return 1;
                    } else if (filetime == newFiletime) {
                        return 0;
                    } else {
                        return -1;
                    }
                }
            });
        }
        return fileList;
    }

    /**
     * 比较List的值
     *
     * @param a
     * @param b
     * @return
     */
    public static <T extends Comparable<T>> boolean compare(List<T> a, List<T> b) {
        if (a.size() != b.size())
            return false;
        Collections.sort(a);
        Collections.sort(b);
        for (int i = 0; i < a.size(); i++) {
            if (!a.get(i).equals(b.get(i)))
                return false;
        }
        return true;
    }
    /**
     * 读取文件内容
     *
     * @param fileName
     * @return
     * @throws EsbSynException
     */
    public static String readToString(String fileName) {
        String encoding = "UTF-8";
        File file = new File(fileName);
        FileInputStream in=null;
        if (!file.exists()) {
            //文件不存在
            String error = "文件：" + fileName + " 不存在";
            logger.error(error);
            throw new EsbSynException(error);
        } else {
            Long filelength = file.length();
            byte[] filecontent = new byte[filelength.intValue()];
            try {
              in = new FileInputStream(file);
                in.read(filecontent);
                in.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                logger.info("获取文件" + fileName + "成功!");
                return new String(filecontent, encoding);
            } catch (UnsupportedEncodingException e) {
                System.err.println("The OS does not support " + encoding);
                e.printStackTrace();

                return null;
            }
        }
    }

    //map转List
    public static List<Map<String, List>> mapToList(Map<String, List> serviceCodeIPMap)   {
        List<Map<String, List>> list = new ArrayList<Map<String, List>>();
        if(serviceCodeIPMap.isEmpty()){

            throw new EsbSynException("读取的配置文件为空.");
        }

        Iterator<Map.Entry<String, List>> entrys = serviceCodeIPMap.entrySet().iterator();

        while (entrys.hasNext()) {
            Map.Entry<String, List> entry = entrys.next();
            String serviceCode = entry.getKey();
            List ipList = entry.getValue();
            Map map = new HashMap();
            map.put("servicecode", serviceCode);
            map.put("ipList", ipList);
            list.add(map);
        }
        return list;

    }


    /**
     * 获取递增序列号
     *
     * @param n
     * @return
     */
    public static String getNum(int n, char[] ary2) {
        String str = String.valueOf(n);
        char[] ary1 = str.toCharArray();
        System.arraycopy(ary1, 0, ary2, ary2.length - ary1.length, ary1.length);
        String result = new String(ary2);
        Date date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
        result = sf.format(date) + "_" + result;
        return result;
    }
    /**
     * 判断是否有重名文件,返回新建文件名
     *
     * @param
     * @param n
     * @return
     */
    public static String getFileName(String path, int n) {
        char[] ary = {'0', '0'};
        String filepath = path + "F5_" + getNum(n, ary) + ".sh";
        File file = new File(filepath);
        if (file.exists()) {
            n++;
            return getFileName(path, n);
        } else {
            return "F5_" + getNum(n, ary) + ".sh";
        }
    }

}
